package czy.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/list")
public class ListController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取指定列表长度
     */
    @GetMapping("/size/{key}")
    public long getSize(@PathVariable String key){
        return this.redisTemplate.opsForList().size(key);
    }

    @GetMapping("/{key}")
    public List<Object> getList(@PathVariable String key) {
        long size = this.redisTemplate.opsForList().size(key);
        return this.redisTemplate.opsForList().range(key, 0, size);
    }

    @GetMapping("/{key}/{start}/{end}")
    public List<Object> getListWithRange(@PathVariable String key, @PathVariable long start, @PathVariable long end) {
        return this.redisTemplate.opsForList().range(key, start, end);
    }

    @GetMapping("/{key}/{index}")
    public Object getObjectWithIndex(@PathVariable String key, @PathVariable long index) {
        return this.redisTemplate.opsForList().index(key, index);
    }

    /**
     * 从右边推入一个元素，即插入到列表末尾
     */
    @PostMapping("/right/push/{key}")
    public long rightPush(@PathVariable String key,@RequestBody Object Object){
        return this.redisTemplate.opsForList().rightPush(key,Object);
    }

    /**
     * 从左边推入一个元素，即插入到列表开头
     */
    @PostMapping("/left/push/{key}")
    public long leftPush(@PathVariable String key,@RequestBody Object Object){
        return this.redisTemplate.opsForList().leftPush(key,Object);
    }

    /**
     * 重置指定下标元素，即替换
     */
    @PostMapping("/{key}/{index}")
    public String setObjectWithIndex(@PathVariable String key, @PathVariable long index, @RequestBody Object Object) {
        this.redisTemplate.opsForList().set(key, index, Object);
        return "设置列表元素成功";
    }

    /**
     * 从右边删除一个元素并返回
     */
    @DeleteMapping("/right/pop/{key}")
    public Object rightPush(@PathVariable String key){
        return this.redisTemplate.opsForList().rightPop(key);
    }

    /**
     * 从左边删除一个元素并返回
     */
    @DeleteMapping("/left/pop/{key}")
    public Object leftPush(@PathVariable String key){
        return this.redisTemplate.opsForList().leftPop(key);
    }

}
